﻿using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Zocono.Infrastructure.Common;
using Zocono.WCS.Domain.DomainRepository;
using Zocono.WCS.Domain.EntityInfo;
using Zocono.WCS.Infrastructure.ApllicationDto.DtoUser;

namespace Zocono.WCS.Domain.UserManageDomain
{
    public class User : IUser
    {
        private readonly IUserRepository _UserRepository;
        private readonly ILogUtil _LogUtil;
        private readonly ISnowflake _Snowflake;
        private readonly IMapper _Mapper;
        private readonly IRoleFunctionRepository _RoleFunctionRepository;

        public User(IUserRepository userRepository, ISnowflake snowflake, IMapper mapper, IRoleFunctionRepository roleFunctionRepository, ILogUtil logUtil)
        {
            _UserRepository = userRepository;
            _Snowflake = snowflake;
            _Mapper = mapper;
            _RoleFunctionRepository = roleFunctionRepository;
            _LogUtil = logUtil;
        }

        #region 属性
        /// <summary>
        /// 主键ID
        /// </summary>
        public long ID { get; set; }

        /// <summary>
        /// 用户名
        /// </summary>
        public string UserName { get; set; }

        /// <summary>
        /// 密码
        /// </summary>
        public string Password { get; set; }

        /// <summary>
        /// 姓名
        /// </summary>
        public string FullName { get; set; }

        /// <summary>
        /// 部门
        /// </summary>
        public string Department { get; set; }

        /// <summary>
        /// 工号
        /// </summary>
        public string JobNumber { get; set; }

        /// <summary>
        /// 角色ID
        /// </summary>
        public long RoleID { get; set; }

        /// <summary>
        /// 是否删除  0 未删除 1 已删除
        /// </summary>
        public bool ISDelete { get; set; }

        /// <summary>
        /// 更新时间
        /// </summary>
        public DateTime UpdateTime { get; set; }

        #endregion

        #region 方法
        public async Task<bool> GetByIdAsync(long Id)
        {
            UserInfo userPo = await _UserRepository.GetByIdAsync(Id);
            _Mapper.Map(userPo, this);
            return userPo == null ? false : true;
        }



        public bool Add()
        {
            bool ret = false;
            try
            {
                List<UserInfo> userInfos = new List<UserInfo>();
                for (int i = 0; i < 1000; i++)
                {
                    UserInfo userPo = new UserInfo();
                    userPo.UserID = _Snowflake.GetId();
                    userPo.UserName = "admin";
                    userPo.Password = GenerateMD5.CreateMD5("8888");
                    userPo.FullName = "";
                    userPo.Department = "";
                    userPo.JobNumber = "";
                    userPo.RoleID = i;
                    userPo.IsDelete = false;
                    userPo.UpdateTime = DateTime.Now;
                    userInfos.Add(userPo);
                }
                UserInfo userPo1 = new UserInfo();
                //userInfos.Add(userPo1);
                _UserRepository.AsTenant().BeginTran();
                //int sum = _UserRepository.AsInsertable(userInfos).ExecuteCommand();
                ret = _UserRepository.InsertRange(userInfos);
                _UserRepository.AsTenant().CommitTran();
                //if (sum > 0) ret = true;
                //_Mapper.Map(userPo, this);
                //return _UserRepository.Insert(userPo);
            }
            catch (Exception ex)
            {
                _UserRepository.AsTenant().RollbackTran();
            }
            return ret;
        }

        public async Task<bool> UpdatePasswordAsync(long ID, string newPassword, string oldPassword)
        {

            //用户名校验
            UserInfo userInfo = await _UserRepository.GetSingleAsync(it => it.UserID == ID && it.IsDelete == false);
            if (userInfo == null)
            {
                throw new DomainException("用户不存在", _LogUtil, MethodBase.GetCurrentMethod().DeclaringType.Name + MethodBase.GetCurrentMethod().Name);
            }
            //密码校验 需加密
            if (userInfo.Password != GenerateMD5.CreateMD5(oldPassword))
            {
                throw new DomainException("旧密码错误", _LogUtil, MethodBase.GetCurrentMethod().DeclaringType.Name + MethodBase.GetCurrentMethod().Name);
            }
            return await _UserRepository.UpdateAsync(it => new UserInfo() { Password = GenerateMD5.CreateMD5(newPassword) }, it => it.UserID == ID);
            //return await _UserRepository.UpdatePasswordAsync(ID, newPassword);
        }

        public async Task<UserInfoDto> LoginAsync(string userName, string password)
        {
            UserInfoDto userInfoDto = new UserInfoDto();
            //用户名校验
            UserInfo userInfo = await _UserRepository.GetSingleAsync(it => it.UserName == userName && it.IsDelete == false);
            if (userInfo == null)
            {
                throw new DomainException("用户名不存在", _LogUtil, MethodBase.GetCurrentMethod().DeclaringType.Name + MethodBase.GetCurrentMethod().Name);
            }
            //密码校验 需加密
            if (userInfo.Password != GenerateMD5.CreateMD5(password))
            {
                throw new DomainException("密码错误", _LogUtil, MethodBase.GetCurrentMethod().DeclaringType.Name + MethodBase.GetCurrentMethod().Name);
            }
            _Mapper.Map(userInfo, userInfoDto);
            return userInfoDto;
        }
        public async Task<UserInfoDto> LoginByIcAsync(string code)
        {


            UserInfoDto userInfoDto = new UserInfoDto();
            //用户名校验
            UserInfo userInfo = await _UserRepository.GetSingleAsync(it => it.IcCode == code && it.IsDelete == false);
            if (userInfo == null)
            {
                throw new DomainException("用户不存在", _LogUtil, MethodBase.GetCurrentMethod().DeclaringType.Name + MethodBase.GetCurrentMethod().Name);
            }
            _LogUtil.Info($"用户刷卡登录{userInfo.UserName}，{code}");
            _Mapper.Map(userInfo, userInfoDto);
            return userInfoDto;
        }
        public async Task<bool> InitPasswordAsync(List<string> userNames)
        {
            return await _UserRepository.InitPasswordAsync(userNames);
        }

        public async Task<long> AddUserInfoAsync(UserInfoDto userInfoDto)
        {
            var check = await _UserRepository.GetListAsync(it => it.UserName == userInfoDto.UserName);
            if (check.Count > 0)
            {
                throw new DomainException("用户名已经存在", _LogUtil, MethodBase.GetCurrentMethod().DeclaringType.Name + MethodBase.GetCurrentMethod().Name);
            }
            UserInfo userInfo = new UserInfo();
            _Mapper.Map(userInfoDto, userInfo);
            userInfo.UserID = _Snowflake.GetId();
            userInfo.Password = GenerateMD5.CreateMD5(userInfo.Password);
            bool ret = await _UserRepository.InsertAsync(userInfo);
            return ret ? userInfo.UserID : 0;
        }

        public async Task<bool> UpdateUserInfoAsync(UserInfoDto userInfoDto)
        {
            var check = await _UserRepository.GetListAsync(it => it.UserName == userInfoDto.UserName && it.UserID != userInfoDto.UserID);
            if (check.Count > 0)
            {
                throw new DomainException("用户名已经存在", _LogUtil, MethodBase.GetCurrentMethod().DeclaringType.Name + MethodBase.GetCurrentMethod().Name);
            }
            UserInfo userInfo = new UserInfo();
            _Mapper.Map(userInfoDto, userInfo);
            return await _UserRepository.UpdateUserInfoAsync(userInfo);
        }

        public async Task<bool> DeleteUserInfoAsync(long ID)
        {
            return await _UserRepository.UpdateAsync(it => new UserInfo() { IsDelete = true }, it => it.UserID == ID);
            //return await _UserRepository.DeleteUserInfoAsync(ID);
        }

        public async Task<UserInfoDto> GetUserInfoAsync(long ID)
        {
            UserInfo userInfo = await _UserRepository.GetByIdAsync(ID);
            if (userInfo == null)
            {
                throw new DomainException($"用户名ID:{ID}查询不存在", _LogUtil, MethodBase.GetCurrentMethod().DeclaringType.Name + MethodBase.GetCurrentMethod().Name);
            }
            UserInfoDto userInfoDto = new UserInfoDto();
            _Mapper.Map(userInfo, userInfoDto);
            return userInfoDto;
        }

        public async Task<List<RoleFunctionInfoDto>> GetRoleFunctionInfoTreeAsync(long roleID)
        {
            List<RoleFunctionInfo> roleFunctionInfos = await _RoleFunctionRepository.GetRoleFunctionInfoTreeAsync(roleID);
            List<RoleFunctionInfoDto> roleFunctionInfoDtos = new List<RoleFunctionInfoDto>();
            _Mapper.Map(roleFunctionInfos, roleFunctionInfoDtos);
            return roleFunctionInfoDtos;
        }

        public async Task<List<RoleFunctionInfoAllShow>> GetRoleFunctionInfoAllTreeAsync(long roleID)
        {
            List<RoleFunctionInfoAllShow> roleFunctionInfos = await _RoleFunctionRepository.GetRoleFunctionInfoAllTreeAsync(roleID);
            //List<RoleFunctionInfoDto> roleFunctionInfoDtos = new List<RoleFunctionInfoDto>();
            //_Mapper.Map(roleFunctionInfos, roleFunctionInfoDtos);
            return roleFunctionInfos;
        }

        public async Task<List<RoleFunctionInfoDto>> GetAllRoleFunctionInfoTreeAsync(long roleID)
        {
            List<RoleFunctionInfo> roleFunctionInfos = await _RoleFunctionRepository.GetAllRoleFunctionInfoTreeAsync(roleID);
            List<RoleFunctionInfoDto> roleFunctionInfoDtos = new List<RoleFunctionInfoDto>();
            _Mapper.Map(roleFunctionInfos, roleFunctionInfoDtos);
            return roleFunctionInfoDtos;
        }

        public async Task<bool> ResetPasswordAsync(long ID, string newPassword)
        {
            return await _UserRepository.UpdatePasswordAsync(ID, newPassword);
        }

        #endregion


    }
}
